package com.shop.cereshop.commons.utils;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
import java.util.UUID;

/**
 * 核销码工具类
 * 
 * @author lx
 */
public class WriteOffUtil {

  /**
   * 生成核销码
   *
   * @return 核销码
   */
  public static String generateWriteOffCode() {
    // 生成唯一标识符
    String uuid = UUID.randomUUID().toString().replace("-", "").toUpperCase();
    // 添加时间戳避免重复
    long timestamp = System.currentTimeMillis();
    // 结合UUID和时间戳生成核销码
    return uuid.substring(0, 8) + timestamp;
  }

  /**
   * 生成核销二维码
   *
   * @param writeOffCode 核销码
   * @return 二维码Base64字符串
   * @throws Exception
   */
  public static String generateWriteOffQRCode(String writeOffCode) throws Exception {
    // 使用QRCodeUtil生成二维码并转换为Base64
    BufferedImage image = QRCodeUtil.createImage(writeOffCode, null, false);
    return imageToBase64(image);
  }

  /**
   * 将BufferedImage转换为Base64字符串
   *
   * @param image 图片
   * @return Base64字符串
   * @throws IOException
   */
  private static String imageToBase64(BufferedImage image) throws IOException {
    ByteArrayOutputStream stream = new ByteArrayOutputStream();
    ImageIO.write(image, "png", stream);
    byte[] bytes = Base64.getEncoder().encode(stream.toByteArray());
    String base64 = new String(bytes, StandardCharsets.UTF_8);
    stream.flush();
    stream.close();
    return "data:image/png;base64," + base64;
  }
}